import React, { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { X, Plus, Trash2, Save } from 'lucide-react'
import { useMutation, useQuery } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { taskApi } from '../services/api'

const TaskEditModal = ({ task, isOpen, onClose, onSuccess }) => {
  const [formData, setFormData] = useState({
    task_name: '',
    description: '',
    variables: {},
    steps: []
  })

  const isEditing = !!task

  // 获取任务详情（编辑模式）
  const { data: taskDetail } = useQuery({
    queryKey: ['task', task?.filename],
    queryFn: () => taskApi.getTask(task.filename).then(res => res.data),
    enabled: isEditing && isOpen,
  })

  // 监听获取到的数据
  useEffect(() => {
    // 当 taskDetail 有数据时（即 useQuery 获取成功后）
    if (isEditing && taskDetail) {
      setFormData({
        task_name: taskDetail.task_name || '',
        description: taskDetail.description || '',
        variables: taskDetail.variables || {},
        steps: taskDetail.high_level_steps?.map(step => ({
          name: step.name || '',
          instruction: step.instruction || ''
        })) || []
      })
    }
  }, [taskDetail, isEditing])

  // 创建任务
  const createTaskMutation = useMutation({
    mutationFn: taskApi.createTask,
    onSuccess: () => {
      toast.success('任务创建成功')
      onSuccess()
    },
    onError: (error) => {
      toast.error(`创建失败: ${error.response?.data?.detail || error.message}`)
    }
  })

  // 更新任务
  const updateTaskMutation = useMutation({
    mutationFn: ({ filename, data }) => taskApi.updateTask(filename, data),
    onSuccess: () => {
      toast.success('任务更新成功')
      onSuccess()
    },
    onError: (error) => {
      toast.error(`更新失败: ${error.response?.data?.detail || error.message}`)
    }
  })

  // 重置表单
  useEffect(() => {
    if (!isEditing && isOpen) {
      setFormData({
        task_name: '',
        description: '',
        variables: {},
        steps: []
      })
    }
  }, [isEditing, isOpen])

  const handleInputChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const handleVariableChange = (key, value, isNewKey = false, oldKey = '') => {
    setFormData(prev => {
      const newVariables = { ...prev.variables }
      
      if (isNewKey && oldKey && oldKey !== key) {
        delete newVariables[oldKey]
      }
      
      if (value === '' && !isNewKey) {
        delete newVariables[key]
      } else if (key) {
        newVariables[key] = value
      }
      
      return {
        ...prev,
        variables: newVariables
      }
    })
  }

  const addVariable = () => {
    const newKey = `变量${Object.keys(formData.variables).length + 1}`
    handleVariableChange(newKey, '', true) 
  }

  const removeVariable = (key) => {
    setFormData(prev => {
      const newVariables = { ...prev.variables }
      delete newVariables[key]
      return {
        ...prev,
        variables: newVariables
      }
    })
  }

  const handleStepChange = (index, field, value) => {
    setFormData(prev => {
      const newSteps = [...prev.steps]
      newSteps[index] = {
        ...newSteps[index],
        [field]: value
      }
      return {
        ...prev,
        steps: newSteps
      }
    })
  }

  const addStep = () => {
    setFormData(prev => ({
      ...prev,
      steps: [...prev.steps, { name: '', instruction: '' }]
    }))
  }

  const removeStep = (index) => {
    setFormData(prev => ({
      ...prev,
      steps: prev.steps.filter((_, i) => i !== index)
    }))
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!formData.task_name.trim()) {
      toast.error('请输入任务名称')
      return
    }
    
    if (formData.steps.length === 0) {
      toast.error('请至少添加一个步骤')
      return
    }

    const submitData = {
      task_name: formData.task_name.trim(),
      description: formData.description.trim(),
      variables: formData.variables,
      steps: formData.steps.filter(step => step.instruction.trim())
    }

    try {
      if (isEditing) {
        await updateTaskMutation.mutateAsync({
          filename: task.filename,
          data: submitData
        })
      } else {
        await createTaskMutation.mutateAsync(submitData)
      }
    } catch (error) {
      console.error('Submit failed:', error)
    }
  }

  if (!isOpen) return null

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        className="bg-white rounded-lg w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col"
        onClick={e => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">
            {isEditing ? '编辑任务' : '创建新任务'}
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 内容 */}
        <form onSubmit={handleSubmit} className="flex-1 flex flex-col overflow-y-auto">
          <div className="p-6 space-y-6">
            {/* 基本信息 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  任务名称 *
                </label>
                <input
                  type="text"
                  className="input w-full"
                  value={formData.task_name}
                  onChange={(e) => handleInputChange('task_name', e.target.value)}
                  placeholder="输入任务名称"
                  required
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  描述
                </label>
                <input
                  type="text"
                  className="input w-full"
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  placeholder="简要描述任务目的"
                />
              </div>
            </div>

            {/* 变量配置 */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <label className="block text-sm font-medium text-gray-700">
                  变量配置
                </label>
                <button
                  type="button"
                  onClick={addVariable}
                  className="text-sm text-blue-600 hover:text-blue-700 flex items-center"
                >
                  <Plus className="w-4 h-4 mr-1" />
                  添加变量
                </button>
              </div>
              
              <div className="space-y-2">
                {Object.entries(formData.variables).map(([key, value]) => (
                  <div key={key} className="flex items-center space-x-2">
                    <input
                      type="text"
                      className="input flex-1"
                      value={key}
                      onChange={(e) => handleVariableChange(e.target.value, value, true, key)}
                      placeholder="变量名"
                    />
                    <span className="text-gray-400">=</span>
                    <input
                      type="text"
                      className="input flex-1"
                      value={value}
                      onChange={(e) => handleVariableChange(key, e.target.value)}
                      placeholder="变量值"
                    />
                    <button
                      type="button"
                      onClick={() => removeVariable(key)}
                      className="p-2 text-red-600 hover:bg-red-50 rounded"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                ))}
                
                {Object.keys(formData.variables).length === 0 && (
                  <p className="text-sm text-gray-500 text-center py-4">
                    暂无变量，点击上方按钮添加
                  </p>
                )}
              </div>
            </div>

            {/* 步骤配置 */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <label className="block text-sm font-medium text-gray-700">
                  高层步骤 *
                </label>
                <button
                  type="button"
                  onClick={addStep}
                  className="text-sm text-primary-600 hover:text-primary-700 flex items-center"
                >
                  <Plus className="w-4 h-4 mr-1" />
                  添加步骤
                </button>
              </div>
              
              <div className="space-y-4">
                {formData.steps.map((step, index) => (
                  <div key={index} className="border border-gray-200 rounded-lg p-4">
                    <div className="flex items-center justify-between mb-3">
                      <span className="text-sm font-medium text-gray-700">
                        步骤 {index + 1}
                      </span>
                      <button
                        type="button"
                        onClick={() => removeStep(index)}
                        className="p-1 text-red-600 hover:bg-red-50 rounded"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                    
                    <div className="space-y-3">
                      <div>
                        <label className="block text-xs font-medium text-gray-600 mb-1">
                          步骤名称
                        </label>
                        <input
                          type="text"
                          className="input w-full"
                          value={step.name}
                          onChange={(e) => handleStepChange(index, 'name', e.target.value)}
                          placeholder="输入步骤名称"
                        />
                      </div>
                      
                      <div>
                        <label className="block text-xs font-medium text-gray-600 mb-1">
                          指令内容 *
                        </label>
                        <textarea
                          className="input w-full min-h-[80px] resize-y"
                          value={step.instruction}
                          onChange={(e) => handleStepChange(index, 'instruction', e.target.value)}
                          placeholder="详细描述执行步骤..."
                          required
                        />
                      </div>
                    </div>
                  </div>
                ))}
                
                {formData.steps.length === 0 && (
                  <div className="text-center py-8 border-2 border-dashed border-gray-300 rounded-lg">
                    <p className="text-sm text-gray-500 mb-2">
                      暂无步骤，请添加至少一个执行步骤
                    </p>
                    <button
                      type="button"
                      onClick={addStep}
                      className="btn-primary"
                    >
                      <Plus className="w-4 h-4 mr-2" />
                      添加第一个步骤
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* 底部操作 */}
          <div className="flex items-center justify-end space-x-3 p-6 border-t border-gray-200 bg-gray-50 sticky bottom-0">
            <button
              type="button"
              onClick={onClose}
              className="btn-secondary"
            >
              取消
            </button>
            <button
              type="submit"
              disabled={createTaskMutation.isLoading || updateTaskMutation.isLoading}
              className="btn-primary disabled:opacity-50"
            >
              {createTaskMutation.isLoading || updateTaskMutation.isLoading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  {isEditing ? '更新中...' : '创建中...'}
                </>
              ) : (
                <>
                  <Save className="w-4 h-4 mr-2" />
                  {isEditing ? '更新任务' : '创建任务'}
                </>
              )}
            </button>
          </div>
        </form>
      </motion.div>
    </motion.div>
  )
}

export default TaskEditModal